<template>
  <div class="batch-upload">
    <div class="batch-upload-left">
      <c-form
        ref="formRef"
        label-width="90px"
        width="100%"
        :loading="loading"
        :model="formData"
        :rows="formRows"
        @submit="onSubmit"
        @reset="onReset"
      >
        <template #imagesStatusSlot>
          <div class="image-state">
            <div class="image-state-item">
              图片数量：
              <span>{{ imageState.totalNum }}</span>
            </div>
            <div class="image-state-item">
              成功数量：
              <span>{{ imageState.successNum }}</span>
            </div>
            <div class="image-state-item">
              失败数量：
              <span>{{ imageState.failNum }}</span>
            </div>
          </div>
        </template>

        <template #squareGridSlot>
          <draggable
            class="square-grid"
            v-model="formData.square_grid_list"
            item-key="imageUrl"
            animation="300"
          >
            <template #item="{ element, index }">
              <div class="square-grid-item">
                <upload-img
                  :desc="false"
                  isPreview
                  v-model="formData.square_grid_list[index]"
                ></upload-img>
              </div>
            </template>
          </draggable>
        </template>
      </c-form>
    </div>
    <div class="batch-upload-right">
      <material-image-read @on-fill="onImageReadFill"></material-image-read>
    </div>
  </div>
</template>

<script setup name="el-encap.table-template.details-page">
import { ref, computed } from 'vue';
import MaterialImageRead from '@/components/material-image-read/index.vue';
import UploadImg from '@/components/upload/upload-img.vue';
import { ElMessage } from 'element-plus';
import draggable from 'vuedraggable';

import { getApi } from '@/utils/tools';

// hooks
import { useForm } from '@/hooks/useForm';
import { useFetch } from '@/hooks/useFetch/index.js';

import { allTypeGroup, userListGroup } from '@/apis/user';
import { listGroup, listUserGroup, createImages } from '@/apis/images';
import { uploadImage } from '@/apis/upload';

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

import { useUserStore } from '@/pinia/modules/user.js';
const userStore = useUserStore();

// router
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();

const emit = defineEmits(['refresh']);

const props = defineProps({
  // 0 普通用户 1 admin
  userType: {
    type: [String, Number],
    default: 0,
  },
});

// 分类列表
const { loading: typeLoading, data: typeGroupData } = useFetch({
  api: props.userType == 1 ? allTypeGroup : userListGroup,
});

// 分组列表
const groupParams = ref({ group_type: '' });
const {
  loading: groupLoading,
  data: groupData,
  queryData: queryListGroup,
} = useFetch({
  api: props.userType == 1 ? listGroup : listUserGroup,
  params: groupParams.value,
});

const { loading, formData, queryDetailsData, submitForm } = useForm({
  initParams: {
    image_type: '',
    image_group_id: '',
    images_list: [],
    isCompress: 1,
    square_grid_list: [
      { url: '' },
      { url: '' },
      { url: '' },
      { url: '' },
      { url: '' },
      { url: '' },
      { url: '' },
      { url: '' },
      { url: '' },
    ],
  },
});

// 获取详情
queryDetailsData({
  api: getApi,
  callBack: (e) => {
    return {
      ...e,
      data: {},
    };
  },
});

const formRows = ref([
  { formType: 'title', label: '基础设置' },
  {
    formType: 'select',
    prop: 'image_type',
    label: '图像类型:',
    optionList: computed(() => typeGroupData.value),
    optionProps: { label: 'label', value: 'value' },
    loading: computed(() => typeLoading.value),
    onChange: (e) => {
      groupParams.value.group_type = e;
      formData.value.image_group_id = '';
      queryListGroup();
    },
  },
  {
    formType: 'select',
    prop: 'image_group_id',
    label: '图像分组:',
    optionList: computed(() => groupData.value.data),
    optionProps: { label: 'name', value: '_id' },
    loading: computed(() => groupLoading.value),
  },
  {
    formType: 'switch',
    prop: 'isCompress',
    label: '是否压缩:',
    activeValue: 1,
    inactiveValue: 0,
  },
  {
    formType: 'upload-imgs',
    prop: 'images_list',
    label: '上传图像:',
    isIf: computed(() => formData.value.image_type != 5),
  },
  {
    formType: 'slot',
    prop: 'square_grid_list',
    slot: 'squareGridSlot',
    label: '上传图像:',
    isIf: computed(() => formData.value.image_type == 5),
  },
  {
    layout: 'item',
    children: [
      {
        formType: 'slot',
        slot: 'imagesStatusSlot',
        label: '上传状态:',
      },
    ],
  },
]);

const formRef = ref(null);
const imageState = ref({ successNum: 0, failNum: 0, totalNum: 0 });
const onSubmit = async () => {
  console.log(formData.value, 'formData', userStore?.userInfo);

  const { image_type, images_list, square_grid_list } = formData.value;

  let imglist = [];

  if (image_type == 5) {
    imglist = square_grid_list;
  } else {
    imglist = images_list;
  }

  imageState.value.successNum = imglist.filter((v) => v.status == 1).length;
  imageState.value.failNum = imglist.filter((v) => v.status == 2).length;
  imageState.value.totalNum = imglist.filter((v) => v.imageUrl).length;

  const userid = props.userType ? -1 : userStore?.userInfo?._id || 0;

  // 单图上传
  if (formData.value.image_type != 5) {
    for (const item of imglist) {
      console.log(item, 'item');
      if (item.status == 0) {
        item.loading = true;
        const form = new FormData();
        form.append('imageType', formData.value.image_type);
        form.append('userid', userid);
        form.append('isCompress', formData.value.isCompress);
        form.append('file', item.file);

        const uploadRes = await uploadImage(form).catch((err) => err);
        if (uploadRes.code === 0) {
          let obj = {
            ...formData.value,
            images: [{ ...item, url: uploadRes.data.url }],
            userid: userid,
            image_type: Number(formData.value.image_type),
          };
          const imageRes = await createImages(obj).catch((err) => err);
          if (imageRes.code === 0) {
            item.url = imageRes.data.host + uploadRes.data.url;
            item.status = 1;
            imageState.value.successNum++;
          } else {
            item.status = 2;
            imageState.value.failNum++;
          }
        } else {
          item.status = 2;
          imageState.value.failNum++;
        }
        item.loading = false;
      }
    }
  }

  // 九宫格
  if (formData.value.image_type == 5 && imglist.filter((v) => v.status == 0).length) {
    let images = [];
    for (const item of imglist) {
      console.log(item, 'item');
      let image = { status: item.status, url: '' };
      if (item.status == 0) {
        item.loading = true;
        const form = new FormData();
        form.append('imageType', formData.value.image_type);
        form.append('userid', userid);
        form.append('isCompress', formData.value.isCompress);
        form.append('file', item.file);
        const uploadRes = await uploadImage(form).catch((err) => err);
        if (uploadRes.code === 0) {
          item.status = 1;
          imageState.value.successNum++;
          image = { ...item, url: uploadRes.data.url };
        } else {
          item.status = 2;
          imageState.value.failNum++;
        }
        item.loading = false;
      }

      images.push(image);
    }
    console.log(images, 'images');

    loading.value = true;
    let obj = {
      ...formData.value,
      images: images.map((v) => {
        return { url: v.url };
      }),
      userid: userid,
      image_type: Number(formData.value.image_type),
    };

    delete obj.square_grid_list;

    const imageRes = await createImages(obj).catch((err) => err);
    loading.value = false;
    if (imageRes.code === 0) {
      formData.value.square_grid_list = images.map((v) => {
        return { url: '' };
      });

      ElMessage.success('上传成功');

      console.log(formData.value.square_grid_list, 'formData.value.square_grid_list ');
    }
  }

  // submitForm({ createApi: getApi, updateApi: getApi });
};

const onReset = () => {
  imageState.value.successNum = 0;
  imageState.value.failNum = 0;
  imageState.value.totalNum = 0;
};

const onImageReadFill = (item) => {
  console.log(item, 'item');
  console.log(formData.value.square_grid_list, 'formData.value.square_grid_list[idx]');

  if (formData.value.image_type == 5) {
    const idx = formData.value.square_grid_list.findIndex((v) => !v.imageUrl);
    console.log(idx, 'idx');

    if (idx + 1 < 9) {
      formData.value.square_grid_list[idx] = item;
    }
  } else {
    formData.value.images_list.push(item);
  }
};

const initData = () => {
  // console.log(route.query, 'route.query');

  const { group_id, image_type } = route.query;

  formData.value.image_type = image_type;
  formData.value.image_group_id = group_id;
};

initData();
</script>

<style lang="scss" scoped>
.image-state {
  display: flex;
  align-items: center;
}

.image-state-item {
  margin-right: 12px;
}

.batch-upload {
  height: 100%;
  display: flex;
  overflow-x: auto;
}

.batch-upload-left {
  min-width: 300px;
  width: 60%;
  overflow: auto;
  padding: 20px;
  box-sizing: border-box;
  @include card-box;
}

.batch-upload-right {
  min-width: 300px;
  width: 40%;
  flex-shrink: 0;
  overflow: auto;
  margin-left: 12px;
  padding: 12px 0;
  box-sizing: border-box;
  @include card-box;

  .is-title {
    margin-left: 12px;
  }
}

.square-grid {
  width: 330px;
  display: flex;
  flex-wrap: wrap;

  .square-grid-item {
    width: calc(100% / 3);
    aspect-ratio: 1/1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
